<?php

namespace app\admin\controller;

use think\Db;
use changpay\ChangPay;
use app\common\controller\chuanglan\ChuanglanSmsApi as CLApi;
use app\admin\controller\system\SmsTemplate;
use app\common\controller\system\Docking;
use app\common\controller\order\Orderget;
class Order extends Common
{
    //	订单审核页面
    public function shenhe()
    {
        $ID = input('ID');
        $data = Db::table('xb_loans_applylist')->where('ID', $ID)->find();
        $this->assign('data', $data);

        return $this->fetch();
    }

    //	订单审核 操作
    public function shenhe_caozuo()
    {
        $this->logs('订单审核');
        $data = input();
        //		p($data);die;
        //根据订单获取用户信息
        $userInfo = db('loans_applylist')->alias('a')
            ->where(['a.ID' => $data['ID']])
            ->join('xb_mem_info m', 'a.UserID = m.ID')
            ->find();

        if ($userInfo['LoanStatus'] == '0') {
            show_error('', '该订单不允许操作');
        }

        //发送审核成功短信通知
        if ($data['LoanStatus'] == 1) {
            //获取短信审核成功短信模板并处理模板内容请求发送短信
            $smsTemp = (new SmsTemplate())->getSmsInfo('check_success');
            $smsTempStr = str_replace('#name#', $userInfo['TrueName'], $smsTemp['Content']);
            //发送短信
            $result1 = (new CLApi('notice'))->sendSMS($userInfo['Mobile'], $smsTempStr);
            $result2 = json_decode($result1, true);

            //写入对接产品记录表
            (new Docking())->addDocking(1, ($result2['code'] == 0) ? 2 : 3, 'chuanglan', '订单审核成功短信', $result1);

            if ($result2['code'] != 0) {
                show_error('', '发送审核成功短信失败');
            }
        }

        //发送审核失败短信通知
        if ($data['LoanStatus'] == 5) {
            //获取审核失败短信并处理模板中变量内容用于请求发送短信
            $smsTemp = (new SmsTemplate())->getSmsInfo('check_failed');
            $smsTempStr = str_replace('#name#', $userInfo['TrueName'], $smsTemp['Content']);
            //发送短信
            $result1 = (new CLApi('notice'))->sendSMS($userInfo['Mobile'], $smsTempStr);
            $result2 = json_decode($result1, true);

            //写入对接产品记录表
            (new Docking())->addDocking(1, ($result2['code'] == 0) ? 2 : 3, 'chuanglan', '订单审核失败短信', $result1);

            if ($result2['code'] != 0) {
                show_error('', '发送审核失败短信失败');
            }
        }

        $temp = [
            'ID' => $data['ID'],               //订单ID
            'LoanStatus' => $data['LoanStatus'],        //订单状态 待放款
            'ShadminID' => session('id'),             //审核人员ID
            'ShTime' => date('Y-m-d H:i:s', time()), //审核时间
            'Status' => $data['LoanStatus'],       //审核状态
            'FkTime' => ($data['LoanStatus'] == 5) ? date('Y-m-d H:i:s', time()) : '', //审核失败的时间
        ];
        if ($data['LoanStatus'] == '1') {
            //			分配放款专员
            $temp['FkadminID'] = kefu('56');
        }

        $upResult = db('loans_applylist')->update($temp);
        if ($upResult) {
            show_success();
        } else {
            show_error();
        }
    }

    //	通讯录
    public function get_list_tongxunlu()
    {
        $ID = input('ID'); //用户ID
        $page = input('page');
        $limit = input('limit');
        $Orderget = new Orderget();
        $where = $Orderget->sorch();
//		p($where);die;
        $Phonelist = Db::table('xb_renzen_social')->where(array('UserID' => $ID))->value('Phonelist');
        if ($Phonelist) {
            $mailList = json_decode($Phonelist, 1);
            $data = json_decode($mailList['mailList'], JSON_UNESCAPED_UNICODE);
            //过滤通讯录姓名中的表情
            foreach ($data as $k => $v) {
                $data[$k]['contact_name'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '表情', $v['contact_name']);
				if($v['contact_name']==$where['TrueName']);
				
				
            }
			$data2=[];
			if(!empty($where['TrueName'])){
				  foreach ($data as $k => $v) {
				     if($v['contact_name']==$where['TrueName']){
				     	$data2[]=$v;
				     }
					 if($v['contact_phone']==$where['Mobile']){
				     	$data2[]=$v;
				     }
                  }
			$data=$data2;
				  
			}
			if(!empty($where['Mobile'])){
				  foreach ($data as $k => $v) {
				    
					 if($v['contact_phone']==$where['Mobile']){
				     	$data2[]=$v;
				     }
                  }
			$data=$data2;
				  
			}
            //		p($data);die;
            //		     //数据分页
            $cuont = count($data);
            $star = ($page - 1) * $limit; //开始截取位置
            $re = array_slice($data, $star, $limit); //分页处理
            if ($re) {
                songsong($re, $cuont);
            } else {
                songsong($re, $cuont);
            }
        } else {
            songsong($re = '0', $cuont = []);
        }
    }

    //	匹配通话
    public function pipei($UserID)
    {
        //查询 社交认证表 中的手机通讯录
        $phonelists = Db::table('xb_renzen_social')->where(['UserID' => $UserID])->value('Phonelist');
        $phonelists_shuju = json_decode($phonelists, 1);
        $phonelists = json_decode($phonelists_shuju['mailList'], JSON_UNESCAPED_UNICODE);
//      p($phonelists);
        //		获取通话排行 //资信报告中获取
        $baogao = Db::table('xb_moxie_report')->where(['UserID' => $UserID])->value('ReportData');
        //		p($baogao);
        $baogaoall = json_decode($baogao, 1);
        $baogao = $baogaoall['call_contact_detail'];
        //		p($baogao);
        //		通话记录
        $data = Db::table('xb_moxie_origin')->where(['UserID' => $UserID])->value('OriginData');
        $CallBill = json_decode($data, 1);
        $callbills = $CallBill['calls'];
        //		p($callbills);die;
        //组合通话记录数据
        $data = []; //组合结束的通话记录数据
         foreach ($callbills as $k => $v) {
             foreach ($v['items'] as $kk => $vv) {
                 $data[] = $vv;
             }
         }
//      p($data);die;
        //		匹配通讯录 次数
        foreach ($phonelists as $k => $v) {
            $sums = '0'; //次数
            foreach ($data as $k2 => $v2) {
                if ($v['contact_phone'] == $v2['peer_number']) {
                    ++$sums;
                }
            }
            $phonelists[$k]['sums'] = $sums;
            $phonelists[$k]['updatetime'] = date('Y-m-d H:i:s');
        }
        //		p($phonelists);die;
        //		匹配通话排名 人名
        foreach ($baogao as $k => $v) {
            foreach ($phonelists as $k2 => $v2) {
                if ($v['peer_num'] == $v2['contact_phone']) {
                    $name = $v2['contact_name'];
                    $baogao[$k]['name'] = $name;
                    $baogao[$k]['updatetime'] = date('Y-m-d H:i:s');
                }
            }
        }
        foreach ($baogao as $key => $value) {
            if (empty($value['name'])) {
                $baogao[$key]['name'] = '不在通讯录';
                $baogao[$key]['updatetime'] = date('Y-m-d H:i:s');
            }
        }
        $baogaoall['call_contact_detail'] = $baogao;
        $baogaoall = json_encode($baogaoall, JSON_UNESCAPED_UNICODE); //最终组合的通排名 人名数据存入数据库
//      p($baogaoall);die;
        $re_paiming = Db::table('xb_moxie_report')->where(['UserID' => $UserID])->update(['ReportData' => $baogaoall]);

        $phonelists_shuju['mailList'] = json_encode($phonelists, 1);
        $phonelists = json_encode($phonelists_shuju, 1);
        $re_cishu = Db::table('xb_renzen_social')->where(['UserID' => $UserID])->update(['Phonelist' => $phonelists]);
        if ($re_paiming && $re_cishu) {
            $result2 = Db::table('xb_mem_info')->where(['ID' => $UserID])->update(['IsPP' => '1']);
        }
    }

    //通话排行
    public function get_list_tonghuapm()
    {
        //  	调用匹配通话接口
        $ID = input('ID');
        $page = input('page');
        $limit = input('limit');
        $TrueName = input('TrueName');
        $this->pipei($ID); //调用匹配通话的函数
        $where = [];
        if ($ID) {
            $where['ID'] = $ID;
        }
        if ($TrueName) {
            $where['TrueName'] = $TrueName;
        }
        $Phonelist = Db::table('xb_moxie_report')->where(['UserID' => $ID])->value('ReportData');
        $Phonelist2 = json_decode($Phonelist, 1)['call_contact_detail'];

        $cuont = count($Phonelist2);
        //数据分页
        $star = ($page - 1) * $limit; //开始截取位置
        $re = array_slice($Phonelist2, $star, $limit); //分页处理

        if ($re) {
            songsong($re, $cuont);
        } else {
            songsong($re, $cuont);
        }
    }

    //	催收记录
    public function get_list_cuishou_jilu()
    {
        $ID = input('ID');
        $page = input('page');
        $limit = input('limit');
        $re = Db::table('xb_beizhu')->where(['AppID' => $ID])->order('ID DESC')->select(); //用户ID
        foreach ($re as $k => $v) {
            $re[$k]['adminID'] = Db::table('xb_sys_administrator')->where(['ID' => $v['adminID']])->value('UserName');

            $RoleID = Db::table('xb_sys_administrator')->where(['ID' => $v['adminID']])->value('RoleID');
            $re[$k]['RoleID'] = Db::table('xb_sys_role')->where(['ID' => $RoleID])->value('Name');
        }
        //数据分页
        $cuont = count($re);
        $star = ($page - 1) * $limit; //开始截取位置
        $re = array_slice($re, $star, $limit); //分页处理
        if ($re) {
            songsong($re, $cuont);
        } else {
            songsong($re, $cuont);
        }
    }

    //	通话记录
    public function get_list_tonghuajilu()
    {
        $ID = input('ID');
        $page = input('page');
        $limit = input('limit');
        $TrueName = input('TrueName');
        $where = [];
        if ($ID) {
            $where['ID'] = $ID;
        }
        if ($TrueName) {
            $where['TrueName'] = $TrueName;
        }
        //	    $data=file_get_contents('./moxie/origin_'.$ID.'.txt');

        $data = Db::table('xb_moxie_origin')->where(['UserID' => $ID])->value('OriginData');
        $CallBill = json_decode($data, 1);
        $CallBill = $CallBill['calls'];
        $datacccc = [];
        foreach ($CallBill as $k => $v) {
            foreach ($v['items'] as $kk => $vv) {
                $datacccc[] = $vv;
            }
        }
        $CallBill = $datacccc;
        //数据分页
        $star = ($page - 1) * $limit; //开始截取位置
        $re = array_slice($CallBill, $star, $limit); //分页处理
        $cuont = count($CallBill);
        if ($re) {
            songsong($re, $cuont);
        } else {
            songsong($re, $cuont);
        }
    }

//    订单列表页面 待审核
    public function index()
    {
        $qudao = $this->qudao(); //调用渠道数据
        $this->assign('qudao', $qudao);
        //		$loanStatus_data = [['name'=>'等待放款','LoanStatus'=>'1'],['name'=>'等待银行打款','LoanStatus'=>'6'],['name'=>'待人工审核','LoanStatus'=>'7']];
        //		P($loanStatus_data);DIE;
        //		$this->assign('loanStatus_data',$loanStatus_data);
        return $this->fetch();
    }

    //    订单列表页面 贷放款
    public function daifangkuan()
    {
        $qudao = $this->qudao(); //调用渠道数据
        $this->assign('qudao', $qudao);
        //		$loanStatus_data = [['name'=>'等待放款','LoanStatus'=>'1'],['name'=>'等待银行打款','LoanStatus'=>'6'],['name'=>'待人工审核','LoanStatus'=>'7']];
        //		P($loanStatus_data);DIE;
        //		$this->assign('loanStatus_data',$loanStatus_data);
        return $this->fetch();
    }

    //    订单列表页面 拒绝
    public function jujue()
    {
        $qudao = $this->qudao(); //调用渠道数据
        $this->assign('qudao', $qudao);
        $loanStatus = ['放款中', '已拒绝', '等待银行打款', '待人工审核'];
        $this->assign('loanStatus', $loanStatus);

        return $this->fetch();
    }

    //	放款页面
    public function editss()
    {
        $ID = input('ID');
        $data = Db::table('xb_loans_applylist')->where('ID', $ID)->find();
        $data['TrueName'] = Db::table('xb_mem_info')->where('ID', $data['UserID'])->value('TrueName');
        $data['Mobile'] = Db::table('xb_mem_info')->where('ID', $data['UserID'])->value('Mobile');
        $data['BankNo'] = Db::table('xb_renzen_bank')->where('UserID', $data['UserID'])->value('BankNo');
        $data['BankName'] = Db::table('xb_renzen_bank')->where('UserID', $data['UserID'])->value('BankName');
        //		p($data);die;
        $this->assign('data', $data);

        return $this->fetch();
    }

    //	放款操作
    //public function fangkuan_caozuo(){
    ////      查看是否是测试环境  1正式 2测试
//      $Payceshi=Db::table('xb_sys_basicinfo')->value('Payceshi');
//      if($Payceshi=='1'){
    //	    $data['TransAmt'] = $data['ApplyMoney'];//放款金额
//      }else{
    //	     $data['TransAmt'] = '0.02';//放款金额
//      }
    //		$data['PartnerId'] =Db::table('xb_sys_inteparameter')->where(['ParaName'=>'changpay'])->value('ParaValue');//商户号
    //		$data['AcctNo'] = $data['BankNo']; //名字
//      $data['AcctName'] = $data['TrueName'];//卡号
//      $data['BankCommonName'] = $data['BankName'];//卡号
    //}

    //	放款操作
    public function edit()
    {
        $this->logs('管理员放款');
        $data = input();
        $LoanStatus = Db::table('xb_loans_applylist')->where(['ID' => $data['ID']])->value('LoanStatus');
        if ($LoanStatus != 1) {
            show_error('', $message = '订单不予许操作');
        }
        $Payceshi = Db::table('xb_sys_basicinfo')->value('Payceshi');
        $Orderget = new Orderget();
        $Payceshi = $Orderget->get_Payceshi(); //获取支付环境
        if ($Payceshi == '1') {
            $data['TransAmt'] = $data['AdoptMoney']; //放款金额
        } else {
            $data['TransAmt'] = '0.02'; //放款金额
        }
        $data['PartnerId'] = $Orderget->get_changpay(); //获取商户号
        $data['AcctNo'] = $data['BankNo']; //名字
        $data['AcctName'] = $data['TrueName']; //卡号
        $data['BankCommonName'] = $data['BankName']; //卡号
        if ($data['pay'] == '3') {//调用银行卡支付
          $changpay = new \changpay\ChangPay();
            $datas = $changpay->payment($data);
            if ($datas['AcceptStatus'] == 'S') {
                $data_update['ID'] = $data['ID'];
                $data_update['OutTradeNo'] = $datas['OutTradeNo']; //支付订单号
            $data_update['LoanStatus'] = '6'; //订单状态
            $data_update['pay'] = $data['pay']; //支付方式
            $data_update['FkadminID'] = session('id'); //放款人员ID
            }
        } else {//支付宝或者微信放款
            $days = Db::table('xb_loans_applylist')->where(['ID' => $data['ID']])->value('ApplyDay'); //根据订单ID获取放款时间
            $data_update['ID'] = $data['ID'];
            $data_update['LoanStatus'] = '2'; //订单状态
            $data_update['pay'] = $data['pay']; //支付方式
            $data_update['OpenTime'] = date('Y-m-d H:i:s'); //放款时间
            $YyFkTime = $Orderget->get_time(date('Y-m-d'), $days); //获取预约还款时间
            $data_update['YyFkTime2'] = $YyFkTime; //预约还款时间  初始时间不会变
            $data_update['YyFkTime'] = $YyFkTime; //预约还款时间   续期增加
            $data_update['FkadminID'] = session('id'); //放款人员ID
        }
        $re = Db::table('xb_loans_applylist')->update($data_update);
        if ($re) {
            if ($data['pay'] != '3') {
                //次数发送 微信支付宝放款的短信
                //获取短信模板与用户信息组合成短信模板发送短信通知
                $smsTemp = (new SmsTemplate())->getSmsInfo('loan_inform');
                $smsTempStr = str_replace(['#name#', '#suffix#', '#refund_time#'], [$data['TrueName'], substr($data['BankNo'], -4), $data_update['YyFkTime']], $smsTemp['Content']);

                //发送短信
                $result1 = (new CLApi())->sendSMS($data['Mobile'], $smsTempStr);
                $result2 = json_decode($result1, true);

                //写入对接产品记录表
                (new Docking())->addDocking(1, ($result2['code'] == 0) ? 2 : 3, 'chuanglan', '订单放款短信通知', $result1);

                if ($result2['code'] != 0) {
                    \Think\Log::record('放款操作 发送短信失败 数据 - '.$result1);
                }
            }
            show_success();
        } else {
            show_error();
        }
    }

    /**
     * 获取订单应还款金额.
     *
     * @param int  $orderInfo 订单信息
     * @param bool $isLimit   是否加入系统最大可逾期天数判断
     *
     * @return int
     */
    public function getOrderShould($orderInfo, $isLimit = true)
    {
        //检测订单是否逾期并获取逾期天数
        $isOrderOverdue = $this->isOrderOverdue($orderInfo, $isLimit);
        if ($isOrderOverdue) {
            //最终还款金额 = 到期应还金额 + 逾期金额
            $orderInfo['daoqiMoney'] = $orderInfo['daoqiMoney'] + $this->getOrderPenalty($orderInfo);
        }

        //获取用户部分还款金额
        $partMoney = $this->getOrderPartMoney($orderInfo);

        //获取用户豁免金额
        $reductionMoney = $this->getOrderReductionMoney($orderInfo);

        //最终还款金额
        return (int) $orderInfo['daoqiMoney'] - ($partMoney + $reductionMoney);
    }

    /**
     * 检测订单是否逾期
     *
     * @param array $orderInfo 订单信息
     * @param bool  $isLimit   是否加入系统最大可逾期天数判断
     *
     * @return int 逾期天数
     */
    public function isOrderOverdue($orderInfo, $isLimit = true)
    {
        $overtimes = date('Y-m-d', strtotime($orderInfo['YyFkTime'])).' 23:59:59';

        //检测是否逾期并返回逾期天数
        if (strtotime($overtimes) < strtotime(date('Y-m-d'))) {
            //获取逾期天数并根据是否根据系统最大可逾期天数 获取订单实际逾期天数
            $days = diffBetweenTwoDays($overtimes, date('Y-m-d'));
            if ($isLimit) {
                $systemDays = (new System())->getSystemInfo();

                return ($days > $systemDays['yuqijifeidays']) ? $systemDays['yuqijifeidays'] : $days;
            } else {
                return $days;
            }
        }

        return 0;
    }

    /**
     * 计算逾期订单逾期罚息.
     *
     * @param araay $orderInfo
     *
     * @return int 订单逾期罚息
     */
    public function getOrderPenalty($orderInfo)
    {
        //检测订单是否逾期并获取逾期天数
        $isOrderOverdue = $this->isOrderOverdue($orderInfo);
        if ($isOrderOverdue) {
            //订单逾期 返回逾期金额 订单申请金额 * 逾期天数 * 逾期利率(%)[订单逾期利率(%)/10]
            return $orderInfo['daoqiMoney'] * $isOrderOverdue * ($orderInfo['yuqililv'] / 10);
        }

        return 0;
    }

    /**
     * 获取订单部分还款的金额.
     *
     * @param int $orderInfo 订单信息
     *
     * @return int 用户借款订单部分还款金额
     */
    public function getOrderPartMoney($orderId)
    {
        $where['OrderSn'] = $orderId['OrderSn'];
        $where['Type'] = 1;

        return db('loans_hklist')->where($where)->sum('TotalMoney');
    }

    /**
     * 获取订单豁免金额.
     *
     * @param array $orderInfo 订单信息
     *
     * @return int 订单豁免金额
     */
    public function getOrderReductionMoney($orderInfo)
    {
        return (int) db('loans_applylist')->alias('a')
            ->join('xb_loans_hklist h', 'a.ID = h.ApplyID')
            ->where(['a.ID' => $orderInfo['ID'], 'h.Type' => '3'])
            ->sum('TotalMoney');
    }
}
